package com.kayo.specimen.service;

import com.kayo.specimen.dao.RoleMapper;
import com.kayo.specimen.dao.RolePrivilegeMapper;
import com.kayo.specimen.model.Privilege;
import com.kayo.specimen.model.Role;
import com.kayo.specimen.model.RolePrivilege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePrivilegeMapper rolePrivilegeMapper;

    @Override
    public int addRoles(Role... roles) {
        for (Role role : roles) {
            role.setId(UUID.randomUUID().toString());
        }
        return roleMapper.insert(roles);
    }

    @Override
    public int updateRoles(Role... roles) {
        return roleMapper.update(roles);
    }

    @Override
    public int removeRoles(String... roleId) {
        return roleMapper.delete(roleId);
    }

    @Override
    public List<Role> getRoles(String id,String name,String order) {
        return roleMapper.select(id,name,order);
    }

    @Override
    public int grantPrivileges(String roleId, String... privileges) {
        int count = 0;
        for (String privilege : privileges) {
            RolePrivilege rolePrivilege = new RolePrivilege(UUID.randomUUID().toString(), roleId, privilege, true);
            count += rolePrivilegeMapper.insert(rolePrivilege);
        }
        return count;
    }

    @Override
    public int revokePrivileges(String roleId, String... privileges) {
        int count = 0;
        for (String privilege : privileges) {
            count += rolePrivilegeMapper.delete(roleId, privilege);
        }
        return count;
    }

    @Override
    public List<Privilege> getGrantedPrivileges(String roleId) {
        return rolePrivilegeMapper.getPrivileges(roleId);
    }
}
